package com.base.dp;

public class MinimumDeleteSum {
    public static void main(String[] args) {

        MinimumDeleteSum mds = new MinimumDeleteSum();
        System.out.println(mds.minimumDeleteSum2("sea", "eat"));
    }

    public int minimumDeleteSum(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();

        int[][] dp = new int[m + 1][n + 1];
        //dp[i][j]表示s1的前i个，和s2的前j个相等需要删除的最小数和
        dp[0][0] = 0;
        for (int i = 1; i <= m; i++) {
            dp[i][0] = s1.charAt(i-1) + dp[i - 1][0];
        }
        for (int j = 1; j <= n; j++) {
            dp[0][j] = s2.charAt(j-1) + dp[0][j - 1];
        }
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j] + (int)s1.charAt(i - 1), dp[i][j - 1] + (int)s2.charAt(j - 1));
                }
            }
        }
        return dp[m][n];
    }


    public int minimumDeleteSum2(String s1, String s2) {
        char[] w1 = s1.toCharArray(),w2 = s2.toCharArray();
        int m = w1.length,n = w2.length;
        int[] dp = new int[n+1];
        for(int j = 1; j <= n; j++){
            dp[j] = dp[j-1] + w2[j-1];
        }
        for(char c : w1){
            int pre = dp[0];
            dp[0] += c;
            for(int j = 1; j <= n; j++){
                int temp = dp[j];
                dp[j] = c == w2[j-1] ? pre : Math.min(dp[j] + c, dp[j-1] + w2[j-1]);
                pre = temp;
            }
        }
        return dp[n];
    }
}
